package com.ejlchina.tool.singleton

import com.ejlchina.tool.bean.BleDeviceBean
import com.huyuhui.fastble.data.BleDevice

object GlobalConnectObject {

    private val connectedDeviceList = mutableListOf<BleDeviceBean>()

    fun getCurrentConnectDeviceList() = connectedDeviceList

    fun addDeviceToConnectList(bleDeviceBean: BleDeviceBean){
        connectedDeviceList.find { it.bleDevice.mac == bleDeviceBean.bleDevice.mac }?: run {
            connectedDeviceList.add(bleDeviceBean)
        }
    }

    fun removeDevice(bleDevice: BleDevice){
        connectedDeviceList.removeIf { it.bleDevice.mac == bleDevice.mac }
    }

    fun resetSelectState(){
        connectedDeviceList.forEachIndexed { index, bleDeviceBean ->
            bleDeviceBean.isSelect = index == 0
        }
    }

    fun getDeviceFromMac(mac: String): BleDeviceBean?{
        return connectedDeviceList.find { it.bleDevice.mac == mac }
    }

    fun setDeviceListIndexFixInfo(){
        connectedDeviceList.forEach { bleDeviceBean ->
            val bucketIndexBean =  GlobalParams.bucketIndexList.find { bucketIndexInfo -> bucketIndexInfo.mac == bleDeviceBean.bleDevice.mac }
            bucketIndexBean?.let {
                bleDeviceBean.deviceNo = it.deviceNo
                bleDeviceBean.bucketNo = it.bucketNo
            }
        }
    }

    fun setBucketInfoToConnectList(){
        connectedDeviceList.onEach { bleDeviceBean ->
            GlobalParams.bucketIndexList.find { it.mac == bleDeviceBean.bleDevice.mac }?.let {
                bleDeviceBean.bucketNo = it.bucketNo
                bleDeviceBean.deviceNo = it.deviceNo
            }
        }
    }

    fun sortConnectByBucketNo(){
        connectedDeviceList.sortBy { it.bucketNo }
    }

    fun setHardAndSoftVersion(bleDevice: BleDevice, softVersion: String, hardVersion: String){
        connectedDeviceList.find { it.bleDevice.mac == bleDevice.mac }?.let { bleDeviceBean ->
            bleDeviceBean.version = softVersion
            bleDeviceBean.hardVersion = hardVersion
        }
    }

    fun setBucketNo(bleDevice: BleDevice,bucketNo: Int){
        connectedDeviceList.find { it.bleDevice.mac == bleDevice.mac }?.let { bleDeviceBean ->
            bleDeviceBean.bucketNo = bucketNo - 79  //这里减去79是因为标记的时候1号标记为80，2号标记为81...
        }
    }
}